package top.lingchen.webfluxdemo1.service.impl;

import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import top.lingchen.webfluxdemo1.entity.User;
import top.lingchen.webfluxdemo1.service.UserService;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 凌宸
 * @create 2021-12-01 下午 5:59
 * @Description
 * @Version 1.0
 */
@Repository
public class UserServiceImpl implements UserService {
    // 创建一个 map 集合存储数据
    private final Map<Integer,User> users = new HashMap<>();

    public UserServiceImpl() {
        this.users.put(1, new User("露西", "女", 20));
        this.users.put(2, new User("杰克", "男", 25));
        this.users.put(3, new User("库里", "男", 30));
    }

    @Override
    public Mono<User> getUserById(int id) {
        return Mono.justOrEmpty(this.users.get(id));
    }

    @Override
    public Flux<User> getAllUsers() {
        return Flux.fromIterable(this.users.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> user) {
        return user.doOnNext(person ->{
            // 向 map 集合里面放值
            int id = users.size() + 1;
            users.put(id,person);
        }).thenEmpty(Mono.empty());
    }
}
